import React, { useEffect, useState, useCallback } from 'react';
import { Form, Input, Button, Space, Switch, Modal, InputNumber, message, Radio, Select, Row, Col, Card, Pagination } from 'antd';
import { SearchOutlined, EditOutlined, PlusOutlined, SaveOutlined, CloseOutlined, IdcardOutlined, UserOutlined, DollarOutlined, CalendarOutlined, FileTextOutlined, CheckCircleTwoTone} from '@ant-design/icons';
import type { IcheckItem } from '../types/checkitem';
import http from '../api/http';
import '../Subscribe/index.css';


const cardStyles = {
  container: {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', 
    gap: 16, 
    maxWidth: 1200, 
    margin: '0 auto',
    padding: '0 12px 16px',
  } as React.CSSProperties,
  card: {
    transition: 'all 0.3s ease',
    boxShadow: '0 2px 6px rgba(0, 0, 0, 0.06)', 
    '&:hover': {
      boxShadow: '0 3px 12px rgba(0, 0, 0, 0.1)',
      transform: 'translateY(-1px)',
    },
  } as React.CSSProperties,
  infoItem: {
    display: 'flex',
    alignItems: 'center',
    marginBottom: 6, // 信息项间距从10→6px
    fontSize: 12, // 字号从14→12px
  } as React.CSSProperties,
  infoLabel: {
    color: '#666',
    width: 80, // 标签宽度从100→80px
    display: 'inline-block',
    fontSize: 12,
  } as React.CSSProperties,
  infoValue: {
    flex: 1,
    color: '#333',
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    fontSize: 12,
  } as React.CSSProperties,
  priceText: {
    color: '#ff4d4f',
    fontWeight: 500,
    fontSize: 13, // 价格字号从15→13px
  } as React.CSSProperties,
  statusWrap: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: 8, // 上间距从12→8px
    paddingTop: 8, // 上内边距从12→8px
    borderTop: '1px dashed #eee',
  } as React.CSSProperties,
};

interface PaginationParams {
  current: number;
  pageSize: number;
  total: number;
}

export default function Subscribe() {
  // 状态管理：分页尺寸适配缩小页面，每页显示更多卡片
  const [pagination, setPagination] = useState<PaginationParams>({
    current: 1,
    pageSize: 4, // 每页数量从6→8（因卡片缩小，可多放2张）
    total: 0,
  });
  const [data, setData] = useState<Array<IcheckItem>>([]);
  const [searchForm] = Form.useForm();
  const [modalForm] = Form.useForm();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalType, setModalType] = useState<'add' | 'edit'>('add');
  const [loading, setLoading] = useState(false);

  // 数据获取与处理方法（保持不变）
  const fetchData = useCallback(() => {
    setLoading(true);
    const { name, zj } = searchForm.getFieldsValue();
    http.getList<IcheckItem>("Checkitem", {
      name,
      zj,
      page: pagination.current,
      size: pagination.pageSize
    }).then(res => {
      setData(res.data);
      setPagination(prev => ({
        ...prev,
        total: res.count,
        current: res.page || prev.current,
      }));
    }).catch(err => {
      message.error('获取数据失败');
      console.error(err);
    }).finally(() => {
      setLoading(false);
    });
  }, [pagination.current, pagination.pageSize, searchForm]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const handleSearch = () => {
    setPagination(prev => ({ ...prev, current: 1 }));
    fetchData();
  };

  const handleStatusChange = (id: number, checked: boolean) => {
    setData(prevData => 
      prevData.map(item => 
        item.id === id ? { ...item, status: checked ? 1 : 0 } : item
      )
    );
    http.put("Checkitem/zt",{id:id,status:checked?1:0}).then(
      res=>{
        if(res.code=='1'){
         message.success(res.msg)
        }
      }
    );
  };

  // 分页处理（保持不变）
  const handlePaginationChange = (page: number, pageSize: number) => {
    setPagination(prev => ({
      ...prev,
      current: page,
      pageSize,
    }));
  };

  const handleAdd = () => {
    setModalType('add');
    modalForm.resetFields();
    modalForm.setFieldsValue({
      minage: 0,
      maxage: 120,
      price: 0,
      id:0,
      sex:'男',
      type:'1',
      affiliationClassify: "一般检查"
    });
    setIsModalOpen(true);
  };

  const handleEdit = (record: IcheckItem) => {
    setModalType('edit');
    modalForm.setFieldsValue({
      id: record.id,
      name: record.name,
      mnemonicName: record.mnemonicName,
      affiliationClassify: record.affiliationClassify,
      sex: record.sex,
      minage: record.minage || 0,
      maxage: record.maxage ||100,
      ckz: record.ckz || '',
      attention: record.attention || '',
      price: record.price || 0,
      remark: record.remark || '',
      type:record.type
    });
    setIsModalOpen(true);
  };

  const handleSubmit = async () => {
    try {
      const values = await modalForm.validateFields();
      setLoading(true);

      if (modalType === 'add') {
        http.post("Checkitem",values).then(res=>{
          if(res.code=="1"){
            message.success(res.msg);
            fetchData(); 
          }else{
            message.error(res.msg);
          }
        });
      } else {
        http.put("Checkitem",values).then(res=>{
          if(res.code=="1"){
            message.success(res.msg);
            fetchData(); 
          }else{
            message.error(res.msg);
          }
        });
      }

      setIsModalOpen(false);
      fetchData();
    } catch (error) {
      console.error('提交失败:', error);
      message.error('提交失败，请检查表单');
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
    
      <div style={{ maxWidth: 1000, margin: '16px auto', padding: '0 12px' }}>
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
          initialValues={{ name: '', zj: '' }}
        >
          <Form.Item name="name">
            <Input placeholder="请输入检查项名称" style={{ width: 160, fontSize: 12 }} />
          </Form.Item>

          <Form.Item name="zj">
            <Input placeholder="请输入助记名" style={{ width: 160, marginLeft: 12, fontSize: 12 }} />
          </Form.Item>

          <Form.Item>
            <Space size="small"> 
              <Button 
                type="primary" 
                htmlType="submit" 
                icon={<SearchOutlined />}
                size="small" 
                style={{ marginLeft: 12 }}
              >
                查询
              </Button>
              
              <Button 
                type="primary" 
                icon={<CheckCircleTwoTone /> }
                onClick={handleAdd}
                size="small" 
                style={{ marginLeft: 6 }}
              >
                新增
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>

     
      <div style={cardStyles.container} >
        {data.length > 0 ? (
          data.map((item) => (
            <Card
              key={item.id}
            
              title={
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <span style={{ fontSize: 14, fontWeight: 500 }}>{item.name}</span>
                  <span style={{ color: '#1890ff', fontSize: 11, display: 'flex', alignItems: 'center' }}>
                    <IdcardOutlined style={{ marginRight: 3, fontSize: 11 }} />
                    编号：{item.id}
                  </span>
                </div>
              }
              style={cardStyles.card}
             
            
              extra={
                <Button 
                  type="primary" 
                  icon={<EditOutlined />}
                  size="mini" 
                  onClick={() => handleEdit(item)}
                  
                >
                  编辑
                </Button>
              }
            >
            
              <div>
                {/* 简称 */}
                <div style={cardStyles.infoItem}>
                  <span style={cardStyles.infoLabel}>简称</span>
                  <span style={cardStyles.infoValue}>{item.mnemonicName || '-'}</span>
                </div>

                {/* 检查项类型 */}
                <div style={cardStyles.infoItem}>
                  <span style={cardStyles.infoLabel}>检查类型</span>
                  <span style={cardStyles.infoValue}>{item.affiliationClassify || '-'}</span>
                </div>

                {/* 所属类型 */}
                <div style={cardStyles.infoItem}>
                  <span style={cardStyles.infoLabel}>所属类型</span>
                  <span style={cardStyles.infoValue}>{item.type === '1' ? '检查' : '检验'}</span>
                </div>

               
                <div style={cardStyles.infoItem}>
                  <span style={cardStyles.infoLabel}>
                    <UserOutlined style={{ marginRight: 3, fontSize: 12 }} />
                    适用性别
                  </span>
                  <span style={cardStyles.infoValue}>{item.sex || '-'}</span>
                </div>

                
                <div style={cardStyles.infoItem}>
                  <span style={cardStyles.infoLabel}>
                    <CalendarOutlined style={{ marginRight: 3, fontSize: 12 }} />
                    年龄范围
                  </span>
                  <span style={cardStyles.infoValue}>
                    {item.minage || 0} - {item.maxage || 120} 岁
                  </span>
                </div>

               
                <div style={cardStyles.infoItem}>
                  <span style={cardStyles.infoLabel}>参考值</span>
                  <span style={cardStyles.infoValue}>{item.ckz || '-'}</span>
                </div>

              
                <div style={cardStyles.infoItem}>
                  <span style={cardStyles.infoLabel}>
                    <DollarOutlined style={{ marginRight: 3, fontSize: 12 }} />
                    价格
                  </span>
                  <span style={{ ...cardStyles.infoValue, ...cardStyles.priceText }}>
                    ¥{Number(item.price || 0).toFixed(2)}
                  </span>
                </div>

              
                <div style={cardStyles.infoItem}>
                  <span style={cardStyles.infoLabel}>
                    <FileTextOutlined style={{ marginRight: 3, fontSize: 12 }} />
                    描述
                  </span>
                  <span style={cardStyles.infoValue} title={item.remark}>
                    {item.remark || '-'}
                  </span>
                </div>

              
                <div style={cardStyles.infoItem}>
                  <span style={cardStyles.infoLabel}>注意事项</span>
                  <span style={cardStyles.infoValue} title={item.attention}>
                    {item.attention || '-'}
                  </span>
                </div>
              </div>

            
              <div style={cardStyles.statusWrap}>
                <span style={{ color: '#666', fontSize: 12 }}>状态</span>
                <Switch
                  checkedChildren="开" 
                  unCheckedChildren="关" 
                  checked={item.status === 1}
                  onChange={(checked) => handleStatusChange(item.id, checked)}
                  size="small" 
                />
              </div>
            </Card>
          ))
        ) : (
        
          <div style={{ gridColumn: '1/-1', textAlign: 'center', padding: '40px 0', color: '#999', fontSize: 12 }}>
            暂无检查项数据，请尝试调整搜索条件
          </div>
        )}
      </div>

     
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '0 12px 16px', textAlign: 'center' }}>
        <Pagination
          current={pagination.current}
          pageSize={pagination.pageSize}
          total={pagination.total}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `共 ${total} 条`} 
          pageSizeOptions={['8', '16', '24']}
          onChange={handlePaginationChange}
          onShowSizeChange={handlePaginationChange}
          size="small" 
        />
      </div>

      
      <Modal
        title={modalType === 'add' ? '新增检查项' : '修改检查项'}
        open={isModalOpen}
        onCancel={() => setIsModalOpen(false)}
        maskClosable={false}
        footer={[
          <Button key="cancel" icon={<CloseOutlined />} onClick={() => setIsModalOpen(false)}>
            取消
          </Button>,
          <Button key="submit" type="primary" icon={<SaveOutlined />} loading={loading} onClick={handleSubmit}>
            保存
          </Button>
        ]}
        width={900}
      
      >
        <Form
          form={modalForm}
          layout="vertical"
          name="checkitem_form"
        >
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="检查项名称"
                rules={[{ required: true, message: '请输入检查项名称' }]}
              >
                <Input maxLength={100} />
              </Form.Item>

              <Form.Item
                name="mnemonicName"
                label="简称"
                rules={[{ required: true, message: '请输入简称' }]}
              >
                <Input maxLength={50} />
              </Form.Item>

                         <Form.Item
                name="affiliationClassify"
                label="检查项类型"
                rules={[{ required: true, message: '请选择检查项类型' }]}
              >
                <Select placeholder="请选择">
                  <Select.Option value="一般检查">一般检查</Select.Option>
                  <Select.Option value="中度检查">中度检查</Select.Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="type"
                label="所属类型"
                rules={[{ required: true, message: '请选择所属类型' }]}
              >
                <Select placeholder="请选择">
                  <Select.Option value="1">检查</Select.Option>
                  <Select.Option value="2">检验</Select.Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="sex"
                label="适用性别"
                rules={[{ required: true, message: '请选择适用性别' }]}
              >
                <Radio.Group buttonStyle="solid">
                  <Radio.Button value="男">男</Radio.Button>
                  <Radio.Button value="女">女</Radio.Button>
                  <Radio.Button value="通用">通用</Radio.Button>
                </Radio.Group>
              </Form.Item>
            </Col>

            <Col span={12}>
              <Space style={{ width: '100%' }}>
                <Form.Item
                  name="minage"
                  label="年龄下限"
                  rules={[{ required: true, message: '请输入年龄下限' }]}
                  style={{ flex: 1 }}
                >
                  <InputNumber min={0} max={120} style={{ width: '100%' }} />
                </Form.Item>

                <Form.Item
                  name="maxage"
                  label="年龄上限"
                  rules={[{ required: true, message: '请输入年龄上限' }]}
                  style={{ flex: 1, marginLeft: 16 }}
                >
                  <InputNumber min={0} max={120} style={{ width: '100%' }} />
                </Form.Item>
              </Space>

              <Form.Item
                name="ckz"
                label="参考值"
              >
                <Input maxLength={200} />
              </Form.Item>

              <Form.Item
                name="price"
                label="价格"
                rules={[{ required: true, message: '请输入价格' }]}
              >
                <InputNumber 
                  min={0} 
                  precision={2} 
                  style={{ width: '100%' }}
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value!.replace(/\¥\s?|(,*)/g, '')}
                />
              </Form.Item>

              <Form.Item
                name="attention"
                label="注意事项"
              >
                <Input.TextArea rows={2} maxLength={500} />
              </Form.Item>

              <Form.Item
                name="remark"
                label="描述"
              >
                <Input.TextArea rows={3} maxLength={1000} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </>
  );
}